package cn.bjit.interceptor;

import cn.bjit.enums.BizCodeEnum;
import cn.bjit.model.LoginUser;
import cn.bjit.util.CommonUtil;
import cn.bjit.util.JWTUtil;
import cn.bjit.util.JsonData;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginUser> threadLocal=new ThreadLocal<>();

    //    该方法将在Controller处理之前进行调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //>>获取accesstoken,一般是登录的时候通过浏览器头传递过来的
        String accessToken = request.getHeader("token");
        if (accessToken == null) { //如果是null说明不是浏览器传递过来的可能是url传递的
            accessToken = request.getParameter("token");
        }
        if (StringUtils.isNotBlank(accessToken)) {
            Claims claims = JWTUtil.checkJWT(accessToken);
            if(claims==null){
                CommonUtil.sendJsonMessage(response, BizCodeEnum.ACCOUNT_UNLOGIN);
                return false;
            }
            long userId = Long.valueOf(claims.get("id").toString());
            String headImg = (String)claims.get("head_img");
            String name = (String)claims.get("name");
            String mail = (String)claims.get("mail");

            LoginUser loginUser = new LoginUser();
            loginUser.setName(name);
            loginUser.setHeadImg(headImg);
            loginUser.setId(userId);
            loginUser.setMail(mail);

            //通过attribute传递用户信息
            //request.setAttribute("loginUser",loginUser);
            //通过threadLocal传递用户登录信息
            threadLocal.set(loginUser);
            return true;
        }
        CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
        return false;
    }

    //    这个方法只会在当前这个Interceptor的preHandle方法返回值为true的时候才会执行。
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    //    该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true时才会执行。
//    该方法将在整个请求完成之后，也就是DispatcherServlet渲染了视图执行。
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
